package com.bugreport.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.bugreport.utils.BugReportException;

public class BugReportJSController extends AbstractController {

	private static final Logger logger = Logger.getLogger(BugReportJSController.class);

	public final static String PARAM_INCLUDE_JQUERY = "includeJQuery";

	public static final String SUCCESS_VIEW = "bugReportJSEntryPoint";

	public static final String SUCCESS_VIEW_APPLICATION_PATH = "applicationPath";
	public static final String SUCCESS_VIEW_INCLUDE_JQUERY = "includeJQuery";

	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		if (METHOD_POST.equals(request.getMethod())) {
			throw new BugReportException(500);
		}

		// computing required variables
		String applicationPath = "http://" + request.getServerName() + ":" + request.getServerPort();
		boolean includeJQuery = request.getParameter(PARAM_INCLUDE_JQUERY) == null
				|| "true".equals(request.getParameter(PARAM_INCLUDE_JQUERY).toLowerCase());

		// log required warning
		if (!includeJQuery) {
			logger.info("You have asked not to include JQuery libraries. Your own Html page must include them and guarantee compatibility with version required by Bug Report. Please refer to documentation to know which jQuery version is necessary.");
		}

		// returning view with all required elements
		ModelAndView mav = new ModelAndView(SUCCESS_VIEW);
		mav.addObject(SUCCESS_VIEW_INCLUDE_JQUERY, includeJQuery);
		mav.addObject(SUCCESS_VIEW_APPLICATION_PATH, applicationPath);
		return mav;
	}
}
